import axios, {HttpStatusCode} from 'axios'
import config from '@/enum/setting'
import {getToken} from "@/utils/token.js";
import showUtil from "@/utils/alert.js";
import store from "@/store";

const httpTime = config.timeout

// 创建axios实例
const axiosService = axios.create({
    // 设置两个参数，一个请求baseurl,一个超时时间
    baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/',
    timeout: httpTime
});

// request拦截器
axiosService.interceptors.request.use(requestConfig => {
        // 每一次请求都手动在请求中增加token请求头
        if (getToken()) {
            requestConfig.headers['Authorization'] = getToken()
        } else {
            // 没有获取到token 默认给json
            requestConfig.headers['Content-Type'] = 'application/json'
        }
        return requestConfig;
    },
    error => {
        return Promise.reject(error)
    })


// response拦截器
axiosService.interceptors.response.use(responseConfig => {
    // 获取返回数据
    if (responseConfig.status === HttpStatusCode.Ok) {
        return responseConfig.data;
    } else {
        showUtil.showError('HTTP返回码值异常')
        return responseConfig.data;
    }
}, error => {
    const axiosData = error.response;
    const httpStatus = axiosData.status;
    const httpData = axiosData.data;
    switch (httpStatus) {
        case 500:
            if (httpData.includes('Proxy error')) {
                showUtil.showError('服务不可用')
            } else {
                showUtil.showError('服务器内部错误')
            }
            break;
        case 401:
            showUtil.showError('登录信息失效，请重新登录')
            // 手动调用logOut
            store.dispatch('LogOut').then(() => {
                location.reload()
            })
            break;
        case 400:
            showUtil.showError('用户名或密码错误')
            break;
        case 403:
            showUtil.showError('拒绝访问')
            break;
        case 404:
            showUtil.showError('请求地址错误')
            break;
        case 408:
            showUtil.showError('请求超时')
            break;
        case 428:
            showUtil.showError(httpData.msg)
            break;
        case 501:
            showUtil.showError('服务未实现')
            break;
        case 502:
            showUtil.showError('网关错误')
            break;
        case 503:
            showUtil.showError('服务不可用')
            break;
        case 504:
            showUtil.showError('网关超时')
            break;
        default:
            break;
    }
    return Promise.reject(error)
})


export default axiosService;
